<template>
  <div class="entrust-list">
    <!-- 搜索和筛选区域 -->
    <GradientCard type="info" class="filter-card">
      <template #default>
        <div class="search-section">
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              placeholder="🔍 搜索委托..."
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <AnimatedButton 
            type="primary" 
            icon="Plus"
            @click="handlePublish"
          >
            发布委托
          </AnimatedButton>
        </div>
      
      <div class="filter-section">
        <div class="filter-tabs">
          <div 
            v-for="category in filterCategories" 
            :key="category.value"
            class="filter-tab"
            :class="{ active: selectedCategory === category.value }"
            @click="selectedCategory = category.value; handleCategoryChange()"
          >
            <span class="tab-icon">{{ category.icon }}</span>
            <span class="tab-label">{{ category.label }}</span>
          </div>
        </div>
        
        <div class="sort-section">
          <span class="sort-label">🎚️ 智能筛选器</span>
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange" class="sort-select">
            <el-option label="最新发布" value="time" />
            <el-option label="报酬最高" value="reward" />
            <el-option label="截止最近" value="deadline" />
            <el-option label="好评优先" value="rating" />
          </el-select>
        </div>
      </div>
      </template>
    </GradientCard>

    <!-- 委托列表 -->
    <div class="list-container">
      <el-empty v-if="entrustList.length === 0" description="暂无委托信息" />
      
      <!-- 急单优先区 -->
      <div v-if="urgentEntrusts.length > 0" class="section-header">
        <h3 class="section-title">🔥 急单优先区</h3>
      </div>
      
      <div class="entrust-grid">
        <GradientCard 
          v-for="item in urgentEntrusts" 
          :key="item.id"
          type="danger"
          class="entrust-card urgent-card"
          @click="handleCardClick(item)"
        >
        <div class="card-header">
          <div class="title-section">
            <h3 class="title">{{ item.title }}</h3>
            <div class="category-badge">
              <span class="category-icon">{{ getCategoryIcon(item.category) }}</span>
              <span class="category-text">{{ item.category }}</span>
            </div>
          </div>
          <div class="reward-section">
            <span class="reward">¥{{ item.reward }}</span>
            <div v-if="isUrgent(item)" class="urgent-badge">
              <el-icon><Timer /></el-icon>
              <span>{{ getTimeLeft(item.deadline) }}</span>
            </div>
          </div>
        </div>
        
        <div class="card-content">
          <p class="description">{{ item.description }}</p>
          
          <div class="info-row">
            <div class="info-item">
              <el-icon><Location /></el-icon>
              <span>{{ item.location }}</span>
            </div>
            <div class="info-item">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(item.createTime) }}</span>
            </div>
          </div>
          
          <div class="publisher-info">
            <div class="publisher-avatar">
              <el-avatar :size="32" :src="item.publisher.avatar">
                {{ item.publisher.name.charAt(0) }}
              </el-avatar>
              <div v-if="item.publisher.isTopUser" class="top-user-badge">
                <el-icon><Crown /></el-icon>
              </div>
            </div>
            <div class="publisher-details">
              <span class="publisher-name">{{ item.publisher.name }}</span>
              <div class="rating-info">
                <StarRating 
                  :model-value="item.publisher.rating" 
                  :readonly="true"
                  :show-score="false"
                />
                <span class="rating-text">{{ item.publisher.rating }}分</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="card-footer">
          <AnimatedButton 
            type="primary" 
            size="small"
            @click.stop="handleAccept(item)"
          >
            接单
          </AnimatedButton>
          <AnimatedButton 
            type="info" 
            size="small"
            @click.stop="handleDetail(item)"
          >
            详情
          </AnimatedButton>
        </div>
      </GradientCard>
      
      <!-- 优质委托区 -->
      <div v-if="qualityEntrusts.length > 0" class="section-header">
        <h3 class="section-title">💼 优质委托</h3>
      </div>
      
      <div class="entrust-grid">
        <GradientCard 
          v-for="item in qualityEntrusts" 
          :key="item.id"
          type="success"
          class="entrust-card quality-card"
          @click="handleCardClick(item)"
        >
          <!-- 复用相同的卡片内容结构 -->
          <div class="card-header">
            <div class="title-section">
              <h3 class="title">{{ item.title }}</h3>
              <div class="category-badge">
                <span class="category-icon">{{ getCategoryIcon(item.category) }}</span>
                <span class="category-text">{{ item.category }}</span>
              </div>
            </div>
            <div class="reward-section">
              <span class="reward">¥{{ item.reward }}</span>
            </div>
          </div>
          
          <div class="card-content">
            <p class="description">{{ item.description }}</p>
            
            <div class="info-row">
              <div class="info-item">
                <el-icon><Location /></el-icon>
                <span>{{ item.location }}</span>
              </div>
              <div class="info-item">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(item.createTime) }}</span>
              </div>
            </div>
            
            <div class="publisher-info">
              <div class="publisher-avatar">
                <el-avatar :size="32" :src="item.publisher.avatar">
                  {{ item.publisher.name.charAt(0) }}
                </el-avatar>
                <div v-if="item.publisher.isTopUser" class="top-user-badge">
                  <el-icon><Crown /></el-icon>
                </div>
              </div>
              <div class="publisher-details">
                <span class="publisher-name">{{ item.publisher.name }}</span>
                <div class="rating-info">
                  <StarRating 
                    :model-value="item.publisher.rating" 
                    :readonly="true"
                    :show-score="false"
                  />
                  <span class="rating-text">{{ item.publisher.rating }}分</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="card-footer">
            <AnimatedButton 
              type="primary" 
              size="small"
              @click.stop="handleAccept(item)"
            >
              接单
            </AnimatedButton>
            <AnimatedButton 
              type="info" 
              size="small"
              @click.stop="handleDetail(item)"
            >
              详情
            </AnimatedButton>
          </div>
        </GradientCard>
      </div>
      
      <!-- 最新发布区 -->
      <div v-if="latestEntrusts.length > 0" class="section-header">
        <h3 class="section-title">🆕 最新发布</h3>
      </div>
      
      <div class="entrust-grid">
        <GradientCard 
          v-for="item in latestEntrusts" 
          :key="item.id"
          type="primary"
          class="entrust-card latest-card"
          @click="handleCardClick(item)"
        >
          <!-- 复用相同的卡片内容结构 -->
          <div class="card-header">
            <div class="title-section">
              <h3 class="title">{{ item.title }}</h3>
              <div class="category-badge">
                <span class="category-icon">{{ getCategoryIcon(item.category) }}</span>
                <span class="category-text">{{ item.category }}</span>
              </div>
            </div>
            <div class="reward-section">
              <span class="reward">¥{{ item.reward }}</span>
            </div>
          </div>
          
          <div class="card-content">
            <p class="description">{{ item.description }}</p>
            
            <div class="info-row">
              <div class="info-item">
                <el-icon><Location /></el-icon>
                <span>{{ item.location }}</span>
              </div>
              <div class="info-item">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(item.createTime) }}</span>
              </div>
            </div>
            
            <div class="publisher-info">
              <div class="publisher-avatar">
                <el-avatar :size="32" :src="item.publisher.avatar">
                  {{ item.publisher.name.charAt(0) }}
                </el-avatar>
                <div v-if="item.publisher.isTopUser" class="top-user-badge">
                  <el-icon><Crown /></el-icon>
                </div>
              </div>
              <div class="publisher-details">
                <span class="publisher-name">{{ item.publisher.name }}</span>
                <div class="rating-info">
                  <StarRating 
                    :model-value="item.publisher.rating" 
                    :readonly="true"
                    :show-score="false"
                  />
                  <span class="rating-text">{{ item.publisher.rating }}分</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="card-footer">
            <AnimatedButton 
              type="primary" 
              size="small"
              @click.stop="handleAccept(item)"
            >
              接单
            </AnimatedButton>
            <AnimatedButton 
              type="info" 
              size="small"
              @click.stop="handleDetail(item)"
            >
              详情
            </AnimatedButton>
          </div>
        </GradientCard>
      </div>
    </div>
    
    <!-- 浮动发布按钮 -->
    <FloatingActionButton 
      :actions="fabActions"
      @action="handleFabAction"
    />
  </div>
  </div>
</template>

<script setup>
import  { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Plus, Clock, Location, Timer, Crown } from '@element-plus/icons-vue'
import GradientCard from './components/GradientCard.vue'
import AnimatedButton from './components/AnimatedButton.vue'
import StarRating from './components/StarRating.vue'
import FloatingActionButton from './components/FloatingActionButton.vue'

/**
 * 委托列表页面组件
 * @description 展示所有可接受的委托，支持搜索、筛选、分页
 */
const router = useRouter()

// 搜索和筛选状态
const searchKeyword = ref('')
const selectedCategory = ref('')
const sortBy = ref('time')

// 委托列表数据
const entrustList = ref([])
const loading = ref(false)

// 筛选分类
const filterCategories = [
  { label: '全部', value: '', icon: '📋' },
  { label: '外卖', value: '外卖', icon: '🍔' },
  { label: '快递', value: '快递', icon: '📦' },
  { label: '打印', value: '打印', icon: '🖨️' },
  { label: '其他', value: '其他', icon: '⋯' }
]

// 浮动按钮操作
const fabActions = [
  {
    id: 'publish',
    label: '发布委托',
    icon: 'Edit',
    color: '#667eea'
  },
  {
    id: 'scan',
    label: '扫码接单',
    icon: 'Scan',
    color: '#4facfe'
  },
  {
    id: 'search',
    label: '快速搜索',
    icon: 'Search',
    color: '#fa709a'
  }
]

// 模拟数据
const mockData = [
  {
    id: 1,
    title: '代取快递',
    category: '快递',
    reward: 15,
    description: '顺丰快递到南门，送到宿舍3号楼，包裹不大，轻便',
    createTime: '2023-11-30T10:30:00Z',
    deadline: '2023-11-30T18:00:00Z',
    location: '南校区',
    publisher: {
      name: '张同学',
      avatar: '',
      rating: 4.2
    },
    status: 'pending'
  },
  {
    id: 2,
    title: '代买午餐',
    category: '外卖',
    reward: 8,
    description: '二食堂麻辣香锅，微辣，不要香菜，送到图书馆3楼',
    createTime: '2023-11-30T09:15:00Z',
    deadline: '2023-11-30T12:00:00Z',
    location: '全校',
    publisher: {
      name: '匿名发布',
      avatar: '',
      rating: 0
    },
    status: 'pending'
  },
  {
    id: 3,
    title: '紧急打印',
    category: '打印',
    reward: 5,
    description: '毕业论文50页，双面打印，送到图书馆3楼，很急',
    createTime: '2023-11-30T08:45:00Z',
    deadline: '2023-11-30T11:00:00Z',
    location: '图书馆',
    publisher: {
      name: '李同学',
      avatar: '',
      rating: 4.5
    },
    status: 'pending'
  }
]

/**
 * 获取类别对应的标签类型
 * @param {string} category - 委托类别
 * @returns {string} 标签类型
 */
const getCategoryType = (category) => {
  const typeMap = {
    '外卖': 'success',
    '快递': 'primary',
    '打印': 'warning',
    '其他': 'info'
  }
  return typeMap[category] || 'info'
}

/**
 * 格式化时间显示
 * @param {string} timeStr - 时间字符串
 * @returns {string} 格式化后的时间
 */
const formatTime = (timeStr) => {
  const now = new Date()
  const time = new Date(timeStr)
  const diff = now - time
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else {
    return `${days}天前`
  }
}

/**
 * 格式化截止时间
 * @param {string} deadlineStr - 截止时间字符串
 * @returns {string} 格式化后的截止时间
 */
const formatDeadline = (deadlineStr) => {
  const deadline = new Date(deadlineStr)
  const now = new Date()
  const diff = deadline - now
  
  if (diff < 0) {
    return '已过期'
  }
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor(diff / (1000 * 60))
  
  if (hours > 0) {
    return `${hours}小时后`
  } else {
    return `${minutes}分钟后`
  }
}

/**
 * 处理搜索
 */
const handleSearch = () => {
  currentPage.value = 1
  fetchEntrustList()
}

/**
 * 处理类别筛选变化
 */
const handleCategoryChange = () => {
  currentPage.value = 1
  fetchEntrustList()
}

/**
 * 处理排序变化
 */
const handleSortChange = () => {
  fetchEntrustList()
}

/**
 * 处理分页大小变化
 * @param {number} size - 新的分页大小
 */
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchEntrustList()
}

/**
 * 处理当前页变化
 * @param {number} page - 新的页码
 */
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchEntrustList()
}

/**
 * 获取委托列表
 */
const fetchEntrustList = async () => {
  loading.value = true
  
  try {
    // TODO: 调用API获取委托列表
    // const res = await getEntrustList({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   keyword: searchKeyword.value,
    //   category: selectedCategory.value,
    //   sortBy: sortBy.value
    // })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟筛选逻辑
    let filteredData = [...mockData]
    
    if (searchKeyword.value) {
      filteredData = filteredData.filter(item => 
        item.title.includes(searchKeyword.value) || 
        item.description.includes(searchKeyword.value)
      )
    }
    
    if (selectedCategory.value) {
      filteredData = filteredData.filter(item => 
        item.category === selectedCategory.value
      )
    }
    
    // 模拟排序逻辑
    filteredData.sort((a, b) => {
      switch (sortBy.value) {
        case 'reward':
          return b.reward - a.reward
        case 'deadline':
          return new Date(a.deadline) - new Date(b.deadline)
        default:
          return new Date(b.createTime) - new Date(a.createTime)
      }
    })
    
    entrustList.value = filteredData
    total.value = filteredData.length
    
  } catch (error) {
    console.error('获取委托列表失败：', error)
    ElMessage.error('获取委托列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 处理卡片点击
 * @param {Object} item - 委托项
 */
const handleCardClick = (item) => {
  router.push(`/entrust/detail/${item.id}`)
}

/**
 * 处理接受委托
 * @param {Object} item - 委托项
 */
const handleAccept = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要接受"${item.title}"这个委托吗？`,
      '确认接受',
      {
        confirmButtonText: '确定接受',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // TODO: 调用API接受委托
    // await acceptEntrust(item.id)
    
    ElMessage.success('委托接受成功！')
    router.push(`/entrust/detail/${item.id}`)
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('接受委托失败：', error)
      ElMessage.error('接受委托失败')
    }
  }
}

/**
 * 处理查看详情
 * @param {Object} item - 委托项
 */
const handleDetail = (item) => {
  router.push(`/entrust/detail/${item.id}`)
}

/**
 * 处理发布委托
 */
const handlePublish = () => {
  router.push('/entrust/publish')
}

/**
 * 处理浮动按钮操作
 * @param {Object} action - 操作对象
 */
const handleFabAction = (action) => {
  switch (action.id) {
    case 'publish':
      router.push('/entrust/publish')
      break
    case 'scan':
      ElMessage.info('扫码功能开发中...')
      break
    case 'search':
      // 聚焦搜索框
      document.querySelector('.search-input input')?.focus()
      break
  }
}

/**
 * 获取分类对应的图标
 * @param {string} category - 分类名称
 * @returns {string} 图标
 */
const getCategoryIcon = (category) => {
  const iconMap = {
    '外卖': '🍔',
    '快递': '📦',
    '打印': '🖨️',
    '其他': '⋯'
  }
  return iconMap[category] || '⋯'
}

/**
 * 判断是否为急单
 * @param {Object} item - 委托项
 * @returns {boolean} 是否为急单
 */
const isUrgent = (item) => {
  const deadline = new Date(item.deadline)
  const now = new Date()
  const diffHours = (deadline - now) / (1000 * 60 * 60)
  return diffHours <= 2 // 2小时内为急单
}

/**
 * 获取剩余时间
 * @param {string} deadline - 截止时间
 * @returns {string} 剩余时间
 */
const getTimeLeft = (deadline) => {
  const deadlineDate = new Date(deadline)
  const now = new Date()
  const diffMinutes = Math.floor((deadlineDate - now) / (1000 * 60))
  
  if (diffMinutes <= 0) return '已过期'
  if (diffMinutes < 60) return `${diffMinutes}min`
  
  const hours = Math.floor(diffMinutes / 60)
  const minutes = diffMinutes % 60
  return `${hours}h${minutes}min`
}

// 计算属性：分类委托
const urgentEntrusts = computed(() => {
  return entrustList.value.filter(item => isUrgent(item))
})

const qualityEntrusts = computed(() => {
  return entrustList.value.filter(item => 
    item.publisher.rating >= 4.5 && !isUrgent(item)
  ).slice(0, 6)
})

const latestEntrusts = computed(() => {
  return entrustList.value.filter(item => 
    !isUrgent(item) && item.publisher.rating < 4.5
  ).slice(0, 6)
})

// 组件挂载时获取数据
onMounted(() => {
  fetchEntrustList()
})
</script>

<style scoped>
.entrust-list {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 20px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  align-items: center;
}

.search-container {
  flex: 1;
  max-width: 400px;
}

.search-input {
  width: 100%;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-tabs {
  display: flex;
  gap: 8px;
}

.filter-tab {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 12px 16px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  min-width: 60px;
}

.filter-tab:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.filter-tab.active {
  background: rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.tab-icon {
  font-size: 20px;
}

.tab-label {
  font-size: 12px;
  font-weight: 500;
}

.sort-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sort-label {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

.sort-select {
  min-width: 120px;
}

.list-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.section-header {
  margin-bottom: 16px;
}

.section-title {
  color: white;
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.entrust-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.entrust-card {
  cursor: pointer;
  transition: all 0.3s ease;
  color: white;
}

.entrust-card:hover {
  transform: translateY(-4px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.title-section {
  flex: 1;
}

.title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: white;
}

.category-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  font-size: 12px;
}

.category-icon {
  font-size: 14px;
}

.category-text {
  font-weight: 500;
}

.reward-section {
  text-align: right;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.reward {
  font-size: 24px;
  font-weight: 700;
  color: #ffd700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.urgent-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: rgba(255, 107, 107, 0.8);
  border-radius: 12px;
  font-size: 12px;
  color: white;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

.card-content {
  margin-bottom: 16px;
}

.description {
  color: rgba(255, 255, 255, 0.9);
  margin: 0 0 12px 0;
  line-height: 1.5;
}

.info-row {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
}

.publisher-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
  border-top: 1px solid rgba(255, 255, 255, 0.2);
}

.publisher-avatar {
  position: relative;
}

.top-user-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 16px;
  height: 16px;
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 8px;
  color: #333;
}

.publisher-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.publisher-name {
  font-size: 14px;
  color: white;
  font-weight: 500;
}

.rating-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-text {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.card-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .entrust-list {
    padding: 16px;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-tabs {
    justify-content: center;
  }
  
  .entrust-grid {
    grid-template-columns: 1fr;
  }
  
  .search-section {
    flex-direction: column;
  }
  
  .search-container {
    max-width: none;
  }
}
</style> 